package com.baymax.study.tuLing.netty.p1_echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty服务端：回响服务端
 *
 * @author baymax
 * @since 2025-06-23
 */
public class EchoServer {
    public final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 9999;
        EchoServer server = new EchoServer(port);
        server.start();
        System.out.println("服务端已关闭");
    }

    private void start() throws InterruptedException {
        // 线程组
        EventLoopGroup group = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            // 初始化ServerBootstrap，用于启动NIO服务端
            ServerBootstrap server = new ServerBootstrap();
            server.group(group, worker)
                .channel(NioServerSocketChannel.class)
                //.option(ChannelOption.AUTO_READ, true)
                .localAddress(port)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });
            // 异步绑定到服务器，sync()会阻塞直到完成
            ChannelFuture future = server.bind().sync();
            // 阻塞主线程，直到服务器的ServerChannel被关闭
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
            worker.shutdownGracefully().sync();
        }

    }
}
